package model

import (
	"crypto/md5"
	"encoding/hex"
)

// 处理session
func LoginSession(mobile, pwd string) (string, error) {
	var user User

	// 1. 处理pwd加密两种方式
	m5 := md5.New()
	m5.Write([]byte(pwd))
	pwd_hash := hex.EncodeToString(m5.Sum(nil))

	// 2. 查询并返回数据
	err := GlobalConn.Select("name").Where("mobile = ?", mobile).Where("password_hash = ?", pwd_hash).Find(&user).Error
	return user.Name, err
}

// 返回用户数据
func GetUserInfo(username string) (User, error) {
	var user User
	err := GlobalConn.Where("name = ?", username).First(&user).Error
	return user, err
}

// 更新用户数据
func UpdateUserInfo(oldname, username, avatar string) error {
	// oldname: 修改前用户名
	// username: 修改后用户名
	// avatar: 用户头像地址
	if username != "" {
		return GlobalConn.Model(&User{}).Where("name = ?", oldname).Updates(User{Name: username}).Error
	} else {
		return GlobalConn.Model(&User{}).Where("name = ?", oldname).Updates(User{Avatar_url: avatar}).Error
	}
}
